<template>
  <div>
    <zm-form :model="form" :rules="formRuleOne" ref="zmForm" label-width="150px">
      <zm-form-item label="关联客户" prop="customerId">
        <zm-data-select :list="myCustomerList" v-model="form.customerId" value-key="id" label-name="customerName" placeholder="请选择销售的客户" class="w300" @change="changeCustomer" />
        <zm-button size="mini" @click="newCustomer" v-if="$route.name !== 'approvalMgr'">
          新建客户
        </zm-button>
      </zm-form-item>
      <zm-form-item label="客户类型" v-if="form.customerId">
        <span>{{ customerTypeName || '--'}}</span>
      </zm-form-item>
      <zm-form-item label="合同形式" prop="contractType" v-if="['1', '2', '4', '6','7'].includes(form.type)">
        <zm-data-select v-model="form.contractType" :list="contractTypeList" placeholder="请选择合同形式" class="w300" />
      </zm-form-item>
      <zm-form-item label="销售单类型">
        <span>{{ typeName }}</span>
      </zm-form-item>
      <zm-form-item label="销售单名称" prop="name">
        <zm-input v-model="form.name" maxlength="70" show-word-limit placeholder="请输入销售单名称，建议不超过70个字" class="w300" disabled />
      </zm-form-item>

      <zm-form-item label="我方信息" prop="companyType" v-if="['1', '2', '4', '5', '6','7'].includes(form.type)">
        <!-- <zm-data-select v-model="form.companyType" api="getOrderCompanyList" label-name="companyName" value-key="companyId" placeholder="请选择签约公司主体信息" class="w300" /> -->
        <el-select v-model="form.companyType" placeholder="请选择签约公司主体信息" class="w300" value-key="companyId" clearable>
          <el-option v-for="(item, index) in companyList" :key="index" :label="item.companyName" :value="item.companyId">
          </el-option>
        </el-select>
      </zm-form-item>
      <zm-form-item label="结算方式" prop="settlementType" v-if="['1', '2', '4', '5', '6','7'].includes(form.type)">
        <zm-data-select v-model="form.settlementType" :list="settlementTypeList" placeholder="请选择该客户的结算方式" class="w300" />
        <tip content="请根据销售单的结算类型，正确选择类型：<br />销售结算：按实际回款金额进行计算提成，若逾期会影响正常提成；<br />周期结算：按固定的周期天数进行计算提成；<br />绑定结算：按卡券绑定账户统计，一般用于营销票；<br />兑换结算：按卡券兑换使用统计，一般用于营销票。"></tip>
      </zm-form-item>
      <zm-form-item :label="urlLabelName" prop="enclosureUrlName">
        <zm-upload v-model="form.enclosureUrlName" @on-remove="onFileRemove" :http-request="fileUpload" accept=".rar,.zip,.doc,.docx,.pdf" :limit="1" :single-file-size="5">
          <zm-button>选择附件</zm-button>
        </zm-upload>
        <span class="fc-gray">支持格式：.rar .zip .doc .docx .pdf ，单个文件不能超过5MB</span>
      </zm-form-item>
      <zm-form-item label="签单日期" prop="signDate">
        <zm-date-picker type="date" v-model="form.signDate" class="w300" />
      </zm-form-item>
      <zm-form-item label="是否开票" prop="isInvoice" v-if="['1', '2', '4', '5', '6','7'].includes(form.type)">
        <zm-data-radio :list="isInvoiceList" v-model="form.isInvoice" class="w300" />
      </zm-form-item>
      <zm-form-item label="预填开票主体" prop="invoiceContent" v-if="['1', '2', '4', '5', '6','7'].includes(form.type) && form.isInvoice === '1'">
        <zm-input v-model.trim="form.invoiceContent" placeholder="请输入客户开票的主体信息" class="w300" />
      </zm-form-item>
      <zm-form-item label="发票类型" prop="invoiceType" v-if="['1', '2', '4', '5', '6','7'].includes(form.type) && form.isInvoice === '1'">
        <zm-data-select v-model="form.invoiceType" :list="invoiceTypeList" placeholder="请选择发票类型" class="w300" />
      </zm-form-item>
      <zm-form-item label="所属公司" prop="companyId">
        <el-select v-model="form.companyObj" placeholder="请选择所属公司" class="w300" value-key="companyId" clearable>
          <el-option v-for="(item, index) in companyList" :key="index" :label="item.companyName" :value="item">
          </el-option>
        </el-select>
      </zm-form-item>
      <!-- 新增【业务场景】字段，可在客户设置中进行业务类型配置 -->
      <zm-form-item label="业务场景" v-if="form.type === '3'" prop="businessScene">
        <el-select class="w300" v-model="form.businessScene" clearable>
          <el-option v-for="(item, index) in businessList" :key="index" :label="item.name" :value="item.value">
          </el-option>
        </el-select>
      </zm-form-item>
      <!-- 包场所属信息 -->
      <zm-form-item label="销售单单价" prop="salePrice" v-if="form.type === '4'">
        <zm-input v-model.trim="form.salePrice" placeholder="0.00" class="w300" disabled>
          <template slot="append">元</template>
        </zm-input>
      </zm-form-item>
      <zm-form-item label="包场人数" prop="number" v-if="form.type === '4'">
        <el-input v-model.trim="form.number" placeholder="0" class="w300" onkeyup="value=value.replace(/[^\d]/g, '')">
          <template slot="append">人</template>
        </el-input>
      </zm-form-item>
      <zm-form-item label="销售单总价" prop="saleTotalPrice" v-if="form.type === '4'">
        <el-input v-model.trim="form.saleTotalPrice" placeholder="0.00" class="w300" onkeyup="value=value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')">
          <template slot="append">元</template>
        </el-input>
      </zm-form-item>
      <zm-form-item label="最低销售单价" prop="minSalePrice" v-if="form.type === '4' && form.id && form.checkStatus === '1'">
        <el-input v-model.trim="form.minSalePrice" placeholder="请输入产品最低销售单价" class="w300">
          <template slot="append">元</template>
        </el-input>
      </zm-form-item>
      <zm-form-item label="提成比例" prop="ruleProportion" v-if="form.type === '4' && form.id && form.checkStatus === '1'">
        <el-input v-model.trim="form.ruleProportion" placeholder="请输入提成比例" class="w300">
          <template slot="append">%</template>
        </el-input>
      </zm-form-item>
      <!-- 客诉所属信息 -->
      <zm-form-item label="投诉类型" prop="complaintType" v-if="form.type === '5'">
        <zm-data-select v-model="form.complaintType" api="getDictList" :params="{type: 'complaintType'}" placeholder="请选择投诉类型" class="w300"></zm-data-select>
      </zm-form-item>
      <zm-form-item prop="complaintRemark" label="备注信息" v-if="form.type === '5'">
        <zm-input v-model="form.complaintRemark" type="textarea" :maxlength="300" placeholder="请填写投诉具体信息及建议" class="w500">
        </zm-input>
      </zm-form-item>
    </zm-form>
  </div>
</template>

<script>
import { getData } from '@/utils/date'

import ZmUpload from '@/components/ZmUpload/components/main'
import uploadApis from '@/api/src/upload'
import publicApis from '@/api/src/public'
import Tip from '@/components/Tip'
import dayjs from 'dayjs'
import { getCustomerType } from '@/api/src/customer'
import { getBusinessList } from '@/api/src/saleOrder'

import {
  contractTypeList,
  settlementTypeList,
  invoiceTypeList,
  isInvoiceList,
  formRuleOne
} from '../const'

export default {
  components: { ZmUpload, Tip },
  props: {
    value: {
      type: Object,
      default () {
        return {}
      }
    },
    myCustomerList: {
      type: Array,
      default () {
        return []
      }
    }
  },
  data () {
    return {
      contractTypeList,
      settlementTypeList,
      invoiceTypeList,
      isInvoiceList,
      companyList: [],

      customerTypeName: '', // 需求 V1.1.0

      businessList: [] // 客情销售单-业务场景下
    }
  },
  computed: {
    form: {
      get () {
        return this.value
      },
      set (val) {
        this.$emit('input', val)
      }
    },
    typeName () {
      let arr = { 0: '', 1: '日常销售单', 2: '特殊销售单', 3: '客情销售单', 5: '客诉销售单', 4: '包场销售单', 6: '实物销售单', 7: '文旅销售单' }
      return arr[+this.form.type]
    },
    urlLabelName () {
      return this.form.type === '5' ? '上传附件' : '上传合同相关附件'
    },
    formRuleOne () {
      return formRuleOne(this.form)
    }
  },
  watch: {
    'form.companyObj' (val) {
      this.$set(this.form, 'companyId', val.companyId)
      this.$set(this.form, 'companyName', val.companyName)
    },
    'form.number' () {
      if (+this.form.type === 4 && this.form.number > 0) {
        this.$set(this.form, 'salePrice', (this.form.saleTotalPrice / this.form.number).toFixed(2))
      }
    },
    'form.saleTotalPrice' () {
      if (+this.form.type === 4 && this.form.number > 0) {
        this.$set(this.form, 'salePrice', (this.form.saleTotalPrice / this.form.number).toFixed(2))
      }
    },
    'form.customerId' () {
      this.getCustomerTypeName()
    }

  },
  created () {
    this.init()
  },
  mounted () {
    this.getCompany()
    if (!this.form.signDate) {
      this.form.signDate = getData('today')
    }
  },
  methods: {
    async getCompany () {
      const _res = await publicApis.getOrderCompanyList()
      this.companyList = _res
    },
    newCustomer () {
      this.$emit('new-customer', true)
    },
    async fileUpload (data) {
      let params = new FormData()
      params.append('fileData', data.file)
      const res = await uploadApis.uploadFile(params)
      this.$set(this.form, 'enclosureUrl', res.url)
      this.$set(this.form, 'enclosureUrlName', res.name)
      return res.url
    },
    onFileRemove (v) {
      this.form.enclosureUrl = ''
      this.form.enclosureUrlName = ''
    },
    changeCustomer (val) {
      let item = this.myCustomerList.find(i => {
        return i.id === val
      })
      let stringName = item.customerName + this.typeName + dayjs().format('YYYY-MM-DD')
      this.$set(this.form, 'name', stringName)
    },
    async getCustomerTypeName () {
      if (!this.form.customerId) {
        return
      }

      const customerData = await getCustomerType({ id: this.form.customerId })
      this.customerTypeName = customerData.customerTypeName
      this.form.rental = customerData.rental
    },
    async handleFormValidate () {
      let _valid = false
      this.$refs.zmForm.validate(valid => {
        _valid = valid
      })
      return new Promise((resolve, reject) => {
        _valid ? resolve() : reject('基本信息')
      })
    },
    init () {
      this.saleOrderGetbusinessList()
    },
    async saleOrderGetbusinessList () {
      this.businessList = await getBusinessList()
    }
  }
}
</script>
